package com.qd.admin.controller;

import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.ApiResultWrapper;
import com.cdqidi.excel.ExcelExport;
import com.cdqidi.util.text.SpringFileUtil;
import com.qd.common.sys.annotation.OperatorInfo;
import com.qd.common.sys.enums.OperatorType;
import com.qd.upload.config.UploadDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 系统导入
 *
 * @author sjk
 */
@RestController
@Slf4j
@Valid
@RequiredArgsConstructor
public class ExcelUploadController {

    private final UploadDTO uploadDto;
    private static final String EXCEL_SUFFIX = ".xlsx";

    /**
     * excel导入
     *
     * @param file 文件支持单个
     * @return 成功 or 失败
     */
    @RequestMapping(value = "/sys/sysExcel/upload")
    @OperatorInfo(title = "excel导入", operator = OperatorType.IMPORT)
    public ApiResultWrapper<Object> upload(@RequestParam("file") MultipartFile file) throws IOException {
        final String suffixName = SpringFileUtil.getFileSuffixName(file);
        if (!EXCEL_SUFFIX.equalsIgnoreCase(suffixName)) {
            return ApiResult.error("不支持的文件后缀");
        }
        final String basePath = uploadDto.getTempPath() + File.separator + "excel";
        final File dic = new File(basePath);
        if (!dic.exists()) {
            final boolean b = dic.mkdirs();
            log.info("创建文件: {},状态: {}", basePath, b);
        }
        final String fileName = UUID.randomUUID().toString();

        final File dest = new File(dic.getPath(), fileName + suffixName);
        file.transferTo(dest);
        return ExcelExport.importExcel(dest);
    }

}
